package com.csi.controller.inteceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

public class FullInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println("token=" + token);
        if (token == null || token.isEmpty()){
//            response.setContentType("application/json;charset=utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            // 构建包含 alert 的 HTML 页面
            String htmlResponse = "<html>" +
                    "<head><title>登录失败</title></head>" +
                    "<body>" +
                    "<script type='text/javascript'>" +
                    "alert('请先登录！');" +
                    "window.location.href = 'http://127.0.0.1:5500/login.html';" + // 跳转到登录页面
                    "</script>" +
                    "</body>" +
                    "</html>";
            out.println(htmlResponse);

//            Result r = new Result("请先登录！",ReturnResults.LOGIN_FAILED);
//            ObjectMapper mapper = new ObjectMapper();
//            String json = mapper.writeValueAsString(r);
//            out.println(json);
            return false;
        }else {
            System.out.println("获取到token！");
            return true;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("request = " + request + ", response = " + response + ", handler = " + handler + ", modelAndView = " + modelAndView);
        System.out.println("Process01Interceptor.postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("request = " + request + ", response = " + response + ", handler = " + handler + ", ex = " + ex);
        System.out.println("Process01Interceptor.afterCompletion");
    }
}
